const Search = require('../utils/search.js')
const { parseTorrentName, rssSubTitleParser } = require('../utils/torrent/torrent-name-parser.js')
const logger = require('../utils/console-logger.js')

const BtSiteModel = require('../models/btsite-model')

const ArrayTool = require('../utils/array-tool')

const fetchTorrents = async (title, year, mediaType, searchOptions) => {
    searchOptions = searchOptions || { filterTitle: true, filterYear: true,  filterMediaType: true }
    const sites = await BtSiteModel.list({sortField: 'order', sortOrder:'asc'}, where => {
        where.whereNotNull('rss').where('rss', '!=', '');
        if (searchOptions.sites && searchOptions.sites.length) where.whereNotIn('id', searchOptions.sites);
    })

    if (!sites.length) {
        logger.info('没有可用的站点');
        return [];
    }

    let keyword = searchOptions.keyword || title;
    // year && (keyword += ` ${year}`)
    const res = await Promise.all(
        sites.map(async r => {
            const rssSearched = await Search.rss(r.rss, { keyword })
            logger.info(`[${r.name}]获取种子数：`, rssSearched.length);
            return rssSearched
    }))
    // console.log('res', res);
    let torrents = res.reduce((a, b) => a.concat(b), [])
    logger.info('总共获取种子数：', torrents.length);
    logger.debug('torrents:', torrents)

    // 标题包含名称过滤
    if (searchOptions.filterTitle) {
        torrents = torrents.filter(item => {
            return item.title.indexOf(title) > -1
        })
        logger.info(`标题包含名称[${title}]过滤后剩余种子数：`, torrents.length);
        logger.debug('torrents:', torrents)
    }
    
    // 标题包含年份过滤
    if (year && searchOptions.filterYear) {
        torrents = torrents.filter(item => {
            return item.title.indexOf(year) > -1
        })
        logger.info(`标题包含年份[${year}]过滤后剩余种子数：`, torrents.length);
        logger.debug('torrents:', torrents)
    }

    // 类型过滤
    if (mediaType && searchOptions.filterMediaType) {
        torrents = torrents.filter(item => {
            return item.mediaType === mediaType
        })
        logger.info(`按类型[${mediaType}]过滤后剩余种子数：`, torrents.length);
        logger.debug('torrents:', torrents)
    }

    return torrents
}

const produceOptions = (torrents, mediaType) => {
    const options = [];
    for (let index = 0; index < torrents.length; index++) {
        const element = torrents[index];
        const title = element.title.replace(/\[.*?\]/g, '')
        // console.log('title', title);

        const meta =  parseTorrentName(title);
        if (!meta) continue;      
        if (mediaType === 'tv') {
            
            const subTitle = element.title.replace(title, ' ').replace(/\[|\]/g, ' ')
            // console.log('subTitle', subTitle);

            // 1.parseTorrentName 其中 season 只解析单季，如多季的种子忽略
            // 没有再进行 getSeasonSingle 从副标题解析单季
            if (meta.season === undefined) {
                meta.season = rssSubTitleParser.getSeasonSingle(subTitle)
            }
            // 2.如果1.中 episodes 无存在则从副标题解析
            if (!meta.episodes || !meta.episodes.length) {
                // 全集数从订阅中获取，这里只判断
                const isAllEpisodes = rssSubTitleParser.isAllEpisodes(subTitle)
                if (isAllEpisodes) {
                    meta.isAllEpisodes = true
                    meta.episodes = []
                } else {
                    const episodes = rssSubTitleParser.getEpisodes(subTitle)
                    if (episodes && episodes.length) {
                        meta.episodes = episodes
                    }
                }
            }
            // 考虑有些标题只有集数没有季数，这里默认为1
            // meta.isAllEpisodes 不加入判断 考虑可能是多季的 多季的种子忽略
            if (meta.season === undefined && (meta.episodes && meta.episodes.length > 0) ) {
                meta.season = 1 
            }
            if (meta.season !== undefined && (meta.isAllEpisodes || (meta.episodes && meta.episodes.length > 0)) ) {
                options.push({
                    torrent: element,
                    meta
                })
                logger.info("剧集解析成功 > ", element.title);
            } else {
                logger.info("剧集解析失败 ! ", element.title);
            }
        } else if (mediaType === 'movie'){
            options.push({
                torrent: element,
                meta
            })
        }
    }
    logger.info('解析成功种子数：', options.length);
    return options;
}

const selectOptionMovie = (options) => {
    
    const pixGourpMinSize = ['1080p', '2160p', ''].map(pix => {
        // 小到大排序
        const pixGroup = options.filter(item => pix === '' ? !item.meta.pix : item.meta.pix === pix).sort((a, b) => {
            if (isNaN(a.torrent.size)) return 1
            if (isNaN(b.torrent.size)) return -1
            return parseInt(a.torrent.size) - parseInt(b.torrent.size)
        })
        // 取最小的
        return pixGroup[0]
    })  
    // console.log('pixGourpMinSize', pixGourpMinSize);
    return pixGourpMinSize.find(item => item)
}


const selectOptionTv = (options, season, lackEpisodes, allEpisodesCount) => {

    // 季数过滤
    options = options.filter(item => item.meta.season === season)
    logger.info(`季数[${season}]匹配种子数：`, options.length);

    // 按包含集数排序
    options = options.sort((a, b) => {
        return b.meta.episodes.length - a.meta.episodes.length
    })
    
    // console.log('options sort episodes.length', options.map(o => {
    //     return {
    //         tTitle: o.torrent.title,
    //         tLink: o.torrent.link,
    //         ...o.meta
    //     }
    // }));

    const findEpisodes = []
    const torrents = []
    let lack = lackEpisodes

    const pixList = ['1080p', '2160p', '']
    for (let i = 0; i < pixList.length; i++) {
        if (!lack.length) break;
        const pix = pixList[i];
        const pixGroup = options.filter(item => pix === '' ? !item.meta.pix : item.meta.pix === pix)

        // 是否允许全集的话且有全集则直接返回
        if (allEpisodesCount && allEpisodesCount === lackEpisodes.length) {
            const allEpisodesOption = pixGroup.find(item => item.meta.isAllEpisodes)
            if (allEpisodesOption) {
                logger.info(`找到季数[${season}]的全集种子：`, allEpisodesOption.torrent.title);
                allEpisodesOption.meta.episodes = lackEpisodes
                return {
                    findEpisodes: lackEpisodes,
                    torrents: [allEpisodesOption]
                }
            }
        }

        for (let index = 0; index < pixGroup.length; index++) {
            const element = pixGroup[index];
            // 跳过全集种子
            if (element.meta.isAllEpisodes) continue;
            // 种子包含的集数完全在订阅的集数中
            const isInclude = element.meta.episodes.every(item => lack.includes(item))
            if (isInclude) {
                findEpisodes.push(...element.meta.episodes)
                torrents.push(element)
                lack = ArrayTool.difference(lackEpisodes, findEpisodes)
                logger.info(`找到季数[${season}]的部分种子：`, element.meta.episodes);
            }
        }
    }

    logger.info(`找到缺失[${lackEpisodes.join(',')}]匹配的种子数：`, torrents.length);

    return {
        findEpisodes: findEpisodes.sort((a,b) => a-b),
        torrents
    }
}

const findMovie = async ({title, year}, searchOptions) => {
    const torrents = await fetchTorrents(title, year, 'movie', searchOptions) // 进行种子初步过滤,站点可能填错考虑不加
    // console.log('torrents', torrents);
    const options = produceOptions(torrents, 'movie') // tv, movie,解析细节差异
    // console.log('options', options);
    const selected = selectOptionMovie(options)
    // console.log('selected', selected.torrent.title);

    return selected
}

const findTv = async ({title, year, season, lackEpisodes, allEpisodesCount}, searchOptions) => {
    const torrents = await fetchTorrents(title, year, 'tv', searchOptions) // 进行种子初步过滤,站点可能填错考虑不加
    // console.log('torrents', torrents);
    const options = produceOptions(torrents, 'tv') // tv, movie,解析细节差异
    // console.log('options', options.map(o => {
    //     return {
    //         tTitle: o.torrent.title,
    //         tLink: o.torrent.link,
    //         ...o.meta
    //     }
    // }));
    const selected =  selectOptionTv(options, season , lackEpisodes, allEpisodesCount)
    // console.log('selected', selected.findEpisodes);
    // 遍历打印seleted
    // selected.torrents.forEach(item => {
    //     console.log(item.torrent.title);   
    // });

    return selected
}

module.exports = {
    findMovie, findTv
}